<template>
  <el-dialog
    :model-value="visible"
    :title="editingDeliveryOrder.delivery_id ? '编辑发货单' : '新增发货单'"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
    @update:model-value="close">
    <el-form
      ref="editFormRef"
      :model="editingDeliveryOrder"
      :rules="editRules"
      label-width="100px"
      v-loading="loading">
      <el-row :gutter="20">
        <!-- 发货日期 -->
        <el-col :span="12">
          <el-form-item label="发货日期" prop="delivery_date">
            <el-date-picker
              v-model="editingDeliveryOrder.delivery_date"
              type="date"
              placeholder="请选择发货日期"
              style="width: 100%"
              value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>

        <!-- 快递公司 -->
        <el-col :span="12">
          <el-form-item label="快递公司" prop="courier_id">
            <el-select
              v-model="editingDeliveryOrder.courier_id"
              placeholder="请选择快递公司"
              style="width: 100%"
              filterable
              @change="onCourierChange">
              <el-option
                v-for="courier in courierOptions"
                :key="courier.courier_id"
                :label="courier.courier_name"
                :value="courier.courier_id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <!-- 快递单号 -->
        <el-col :span="12">
          <el-form-item label="快递单号" prop="tracking_number">
            <el-input
              v-model="editingDeliveryOrder.tracking_number"
              placeholder="请输入快递单号" />
          </el-form-item>
        </el-col>

        <!-- 发货人 -->
        <el-col :span="12">
          <el-form-item label="发货人" prop="delivered_by">
            <el-input
              v-model="editingDeliveryOrder.delivered_by"
              placeholder="请输入发货人" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 备注 -->
      <el-form-item label="备注" prop="notes">
        <el-input
          v-model="editingDeliveryOrder.notes"
          type="textarea"
          :rows="3"
          placeholder="请输入备注" />
      </el-form-item>

      <!-- 关联订单 -->
      <el-form-item label="关联订单">
        <el-button type="primary" @click="showOrderSelectionDialog">选择订单</el-button>
        <div class="selected-orders" v-if="selectedOrders.length > 0">
          <el-tag
            v-for="order in selectedOrders"
            :key="order.order_id"
            closable
            @close="removeOrder(order)">
            {{ order.order_number }}
          </el-tag>
        </div>
        <div v-else class="no-orders">
          暂无关联订单
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saveLoading">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  deliveryOrder: {
    type: Object,
    default: () => ({
      delivery_id: '',
      delivery_date: '',
      courier_id: '',
      courier_name: '',
      tracking_number: '',
      delivered_by: '',
      notes: '',
      order_ids: []
    })
  },
  courierOptions: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  },
  saveLoading: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emit = defineEmits([
  'update:visible',
  'update:deliveryOrder',
  'save',
  'close',
  'show-order-selection',
  'remove-order',
  'courier-change'
])

// 表单引用
const editFormRef = ref(null)

// 编辑表单验证规则
const editRules = {
  delivery_date: [
    { required: true, message: '请选择发货日期', trigger: 'change' }
  ],
  courier_id: [
    { required: false, message: '请选择快递公司', trigger: 'change' }
  ]
}

// 已选择的订单
const selectedOrders = computed(() => {
  return props.deliveryOrder.order_ids.map(id => {
    // 注意：这里需要父组件传递订单列表数据来获取完整信息
    return { order_id: id, order_number: `订单${id}` }
  })
})

// 编辑中的发货单数据（本地副本）
const editingDeliveryOrder = computed({
  get: () => props.deliveryOrder,
  set: (value) => emit('update:deliveryOrder', value)
})

// 关闭对话框
const handleClose = () => {
  emit('close')
}

// 关闭对话框
const close = () => {
  emit('update:visible', false)
}

// 保存发货单信息
const handleSave = async () => {
  try {
    await editFormRef.value.validate()
    emit('save', editingDeliveryOrder.value)
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.warning('请填写完整的发货单信息')
  }
}

// 显示订单选择对话框
const showOrderSelectionDialog = () => {
  emit('show-order-selection')
}

// 移除订单
const removeOrder = (order) => {
  emit('remove-order', order)
}

// 当快递公司选择变化时
const onCourierChange = (courierId) => {
  emit('courier-change', courierId)
}
</script>

<style scoped>
.selected-orders {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.no-orders {
  margin-top: 10px;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}
</style>
